/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.tad.cdi.mods.properties;

import com.tad.cdi.mods.properties.annotations.DBConfiguration;
import com.tad.cdi.mods.properties.cache.PropertyCache;
import java.util.List;
import java.util.Properties;
import javax.ejb.Singleton;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.slf4j.Logger;

/**
 *
 * @author johnament
 */
@Singleton
public class DBConfigProducer {
    @PersistenceContext(unitName="ConfigurationPU")
    EntityManager em;

    @Inject Logger logger;
    @Inject PropertyCache propertyCache;
    
    @Produces @DBConfiguration("")
    public Properties produceDatabaseProperties(InjectionPoint ip) {
        String value = ip.getAnnotated().getAnnotation(DBConfiguration.class).value();
        Properties props;
        if(propertyCache.containsKey(value)) {
            props = propertyCache.get(value);
        } else {
            logger.info("creating properties for :"+value);
            props = createProperties(value);
            propertyCache.add(value,props);
        }
        return props;
    }

    private Properties createProperties(String value) {
        Properties props = new Properties();
        List<Object[]> dbProps = em.createNativeQuery(value).getResultList();
        for(Object[] kv : dbProps) {
            props.setProperty(kv[0].toString(), kv[1].toString());
        }
        return props;
    }
}
